package edu.ynu.se.xiecheng.achitectureclass.common.utils;

import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

public class TokenUtil2 {

    // 配置常量
    private static final String TOKEN_URL = "http://42.193.14.241:7000/ysapi/subAccount/getToken";
    private static final String ACCOUNT_ID = "1ca7f0ab24ba41b291346347ec30140e";

    // 可选：缓存 Token 和过期时间
    private static String cachedToken = null;
    private static long tokenExpiryTime = 3600; // Token 缓存过期时间

    /**
     * 获取 Access Token
     * @return Access Token 字符串
     */
    public static String fetchToken() {
        // 如果缓存的 Token 未过期，直接返回缓存的 Token
        if (cachedToken != null && System.currentTimeMillis() < tokenExpiryTime) {
            return cachedToken;
        }

        // 请求头配置
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON); // 设置请求为 JSON 格式

        // 请求体配置
        Map<String, String> requestBody = new HashMap<>();
        requestBody.put("accountId", ACCOUNT_ID);

        // 将请求体封装为 HttpEntity
        HttpEntity<Map<String, String>> requestEntity = new HttpEntity<>(requestBody, headers);

        // 发送 POST 请求
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<Map> response = restTemplate.exchange(TOKEN_URL, HttpMethod.POST, requestEntity, Map.class);

        // 解析响应
        if (response.getStatusCode() == HttpStatus.OK) {
            Map<String, Object> responseBody = response.getBody();
            if (responseBody != null && responseBody.get("data") instanceof Map) {
                Map<String, Object> data = (Map<String, Object>) responseBody.get("data");
                String token = (String) data.get("accessToken");
                int expiresIn = 7200; // 此 API 的 token 有效期为 7200 秒

                // 缓存 Token 和过期时间
                cachedToken = token;
                tokenExpiryTime = System.currentTimeMillis() + (expiresIn * 1000L);

                return token;
            } else {
                throw new RuntimeException("Invalid token response format");
            }
        } else {
            throw new RuntimeException("Failed to fetch token. Status code: " + response.getStatusCode());
        }
    }

    /**
     * 主方法，用于测试 Token 获取功能
     */
//    public static void main(String[] args) {
//        try {
//            String token = fetchToken();
//            System.out.println("Access Token: " + token);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }
}
